package com.czy.owner.ui.order;


import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.czy.owner.R;
import com.czy.owner.adapter.AddressAdapter;
import com.czy.owner.adapter.OrderEvaluateAdapter;
import com.czy.owner.api.CommentGoodsApi;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.CommentGoodsModel;
import com.czy.owner.entity.EvaluateUpdateImgModel;
import com.czy.owner.entity.OrderInfoDetailModel;
import com.czy.owner.entity.OrderItemsBean;
import com.czy.owner.entity.OrdersListModel;
import com.czy.owner.entity.UpLoadUserPortraitModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.net.utils.MyLoadView;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.easyrecycleview.EasyRecyclerView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileInputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by wangyang on 2017/6/8 0008.
 * 添加评价
 */

public class EvaluateActivity extends BaseActivity {
    @BindView(R.id.easy_recycleview)
    EasyRecyclerView easyRecycleview;
    private List<OrderInfoDetailModel.OrderItemsBean> listDetail;
    private List<OrdersListModel.ListBean.OrderItemsBean> mList;
    private List<OrderItemsBean> list = new ArrayList<>();
    private int userOrderId;
    private OrderEvaluateAdapter adapter;
    private Activity activity;
    private CommentGoodsModel mCommentGoodsModel;
    private int updateCount;
    private MyLoadView myLoadView;
    private boolean isFromDetail = false;

    @Override
    protected int attachLayoutRes() {
        return R.layout.common_activity_easyrecycleview;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.person_my_order_evaluate);
        myLoadView = new MyLoadView(EvaluateActivity.this, "正在上传图片", false, true);
        activity = this;

        isFromDetail = getIntent().getBooleanExtra("isFromDetail", false);
        userOrderId = getIntent().getIntExtra("userOrderId", 0);

        if (isFromDetail) {
            listDetail = (List<OrderInfoDetailModel.OrderItemsBean>) getIntent().getSerializableExtra("orderItemsDetail");
            if (listDetail != null && listDetail.size() > 0) {
                for (int i = 0; i < listDetail.size(); i++) {
                    String refundsStatus = listDetail.get(i).getRefundsStatus();
                    String isRefund = listDetail.get(i).getIsRefund();
                    String refundsType = listDetail.get(i).getRefundsType();
                    MyLog.e("yang","refundsStatus=="+refundsStatus+"\nisRefund=="+isRefund+"\nrefundsType=="+refundsType);
                    if (isRefund.equals("true") && refundsStatus.equals("complete") && refundsType.equals("receiveGoods")) {

                    } else if (isRefund.equals("true") && refundsStatus.equals("complete") && refundsType.equals("notReceiveGoods")) {

                    } else {
                        String logo = listDetail.get(i).getLogo();
                        String itemName = listDetail.get(i).getItemName();
                        double price = listDetail.get(i).getPrice();
                        int count = listDetail.get(i).getCount();
                        String specGroupKey = listDetail.get(i).getSpecGroupKey();
                        String goodsId = listDetail.get(i).getItemTypeId();
                        int orderItemId = listDetail.get(i).getOrderItemId();
                        String specValue = listDetail.get(i).getSpecValue();
                        list.add(new OrderItemsBean(logo, itemName, price, count, specGroupKey, goodsId, orderItemId,specValue));
                    }


                }

            }
        } else {
            mList = (List<OrdersListModel.ListBean.OrderItemsBean>) getIntent().getSerializableExtra("orderItemsList");
            if (mList != null && mList.size() > 0) {
                for (int i = 0; i < mList.size(); i++) {
                    String refundsStatus = mList.get(i).getRefundsStatus();
                    String isRefund = mList.get(i).getIsRefund();
                    String refundsType = mList.get(i).getRefundsType();
                    if (isRefund.equals("true") && refundsStatus.equals("complete") && refundsType.equals("receiveGoods")) {

                    } else if (isRefund.equals("true") && refundsStatus.equals("complete") && refundsType.equals("notReceiveGoods")) {

                    } else {
                        String logo = mList.get(i).getLogo();
                        String itemName = mList.get(i).getItemName();
                        double price = mList.get(i).getPrice();
                        int count = mList.get(i).getCount();
                        String specGroupKey = mList.get(i).getSpecGroupKey();
                        String goodsId = mList.get(i).getItemTypeId();
                        int orderItemId = mList.get(i).getOrderItemId();
                        String specValue = mList.get(i).getSpecValue();
                        list.add(new OrderItemsBean(logo, itemName, price, count, specGroupKey, goodsId, orderItemId,specValue));
                    }

                }
            }
        }
        getData();
    }

    @Override
    protected void updateViews() {

    }

    private void getData() {
        easyRecycleview.setLayoutManager(new LinearLayoutManager(this));
        easyRecycleview.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, R.drawable.shape_shopping_strategy_divider_decoration));
        easyRecycleview.setAdapter(adapter = new OrderEvaluateAdapter(this, activity));
        adapter.addAll(list);


        adapter.addFooter(new RecyclerArrayAdapter.ItemView() {
            @Override
            public View onCreateView(ViewGroup parent) {
                LayoutInflater inflater = LayoutInflater.from(EvaluateActivity.this);
                View view = inflater.inflate(R.layout.footer_view_address, null);
                Button btnAddress = (Button) view.findViewById(R.id.btn_add_address);
                btnAddress.setText("发表评论");
                btnAddress.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        for (int i = 0; i < adapter.getAllData().size(); i++) {
                            if (adapter.getAllData().get(i).getStart() == 0.0) {
                                PhoneUtils.ShowToastMessage(EvaluateActivity.this, "请添加商品星级评价");
                                return;
                            }
                        }


                        updateCount = 0;
                        mCommentGoodsModel = new CommentGoodsModel();
                        mCommentGoodsModel.setUserOrderId(userOrderId);
                        List<CommentGoodsModel.CommentsBean> commentGoodsModelList = new ArrayList<>();
                        for (int i = 0; i < adapter.getAllData().size(); i++) {
                            CommentGoodsModel.CommentsBean commentsBeen = new CommentGoodsModel.CommentsBean();
                            commentsBeen.setGoodsId(adapter.getAllData().get(i).getGoodsId());
                            commentsBeen.setStar(adapter.getAllData().get(i).getStart());
                            commentsBeen.setContent(adapter.getAllData().get(i).getContent());
                            commentsBeen.setSpecGroupKey(adapter.getAllData().get(i).getSpecGroupKey());
                            commentsBeen.setOrderItemId(adapter.getAllData().get(i).getOrderItemId());
                            commentGoodsModelList.add(commentsBeen);

                            if (adapter.getAllData().get(i).getPicList().size() > 0) {
                                synchronized (EvaluateActivity.this) {
                                    updateCount++;
                                    UpdatePic(adapter.getAllData().get(i).getPicList(), i);
                                }
                            }
                        }
                        mCommentGoodsModel.setComments(commentGoodsModelList);

                        if (updateCount == 0) {
                            commentGoods(new Gson().toJson(mCommentGoodsModel));
                        }
                    }
                });
                return view;
            }

            @Override
            public void onBindView(View headerView) {

            }
        });
    }
    //上传图片
    private void UpdatePic(List<String> picList, final int pos) {
        myLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.RES_UPLOAD;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(EvaluateActivity.this).getSession());
        params.setMultipart(true);
        try {
            if (picList.size() > 0) {
                for (int i = 0; i < picList.size(); i++) {
                    params.addBodyParameter("file" + (i + 1), new FileInputStream(new File(picList.get(i))), "img/jpg", "pic" + i + ".jpg");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String data = PhoneUtils.checkResponseFlag(EvaluateActivity.this, result);
                List<EvaluateUpdateImgModel> list = new Gson().fromJson(data, new TypeToken<List<EvaluateUpdateImgModel>>() {
                }.getType());
                List<CommentGoodsModel.CommentsBean.PicsBean> mPicList = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    CommentGoodsModel.CommentsBean.PicsBean picsBean = new CommentGoodsModel.CommentsBean.PicsBean();
                    picsBean.setUrl(list.get(i).getUrl());
                    mPicList.add(picsBean);
                }
                mCommentGoodsModel.getComments().get(pos).setPics(mPicList);


            }


            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("update", "onError==" + ex.toString());
                mLoadView.CancleLoadView();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                synchronized (EvaluateActivity.this) {
                    updateCount--;
                    if (updateCount == 0) {
                        commentGoods(new Gson().toJson(mCommentGoodsModel));
                    }
                }

            }
        });


    }


    private void commentGoods(String json) {
        CommentGoodsApi commentGoodsApi = new CommentGoodsApi(new HttpOnNextListener<String>() {
            @Override
            public void onNext(String data) {
                PhoneUtils.ShowToastMessage(EvaluateActivity.this, "评价成功");
                RxBus.getDefault().post(Constants.ORDER_EVALUATE_SECCESS_CODE, new CommonEvent("评价成功"));
                Intent intent = new Intent();
                intent.setAction(OrderActivity.orderAction);
                intent.putExtra("currentId", 0);
                sendBroadcast(intent);
                finish();
                mLoadView.CancleLoadView();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                mLoadView.CancleLoadView();
                PhoneUtils.ShowToastMessage(EvaluateActivity.this, e.getMessage());
            }

        }, this);
        commentGoodsApi.setSession(UserHelper.getInstance().getSessionInfoModel(EvaluateActivity.this).getSession());
        commentGoodsApi.setJson(json);
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(commentGoodsApi);
    }


    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(new ContextWrapper(newBase) {
            @Override
            public Object getSystemService(String name) {
                if (Context.AUDIO_SERVICE.equals(name))
                    return getApplicationContext().getSystemService(name);
                return super.getSystemService(name);
            }
        });
    }
}
